//
//  MeLoginScollview.m
//  ZITHER
//
//  Created by weixin on 2018/9/26.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "MeLoginScollview.h"
#import "MeSetUsetImg.h"
#import "NetworkEngine.h"
#import "NetworkEngine+imageCloudManager.h"
#import "Ugc_Receive_VC_WX.h"
#import "Ugc_MyLaud_VC.h"
#import <UMPush/UMessage.h>



@implementation MeLoginScollview

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
    }
    return self;
}

-(void)setUI{
    
    [self addSubview:self.picUser];
    [self addSubview:self.labUserName];
    [self addSubview:self.labUserPhone];
    [self addSubview:self.btnReceive];
    [self addSubview:self.btnHome];
    [self addSubview:self.btnLike];
    [self addSubview:self.btnSetUP];
    
}

-(UIImageView *)picUser{
    if (!_picUser) {
        _picUser = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenW/2-kScreenW/100*33/2, kScreenH/100*12, kScreenW/100*33, kScreenW/100*33)];
        [_picUser setCornerRadiusWithRadius:kScreenW/100*33/2 isMasks:YES];
        _picUser.backgroundColor = [UIColor randomColor];
        _picUser.userInteractionEnabled = YES;
        _picUser.contentMode = 2 ;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        @weakify(self);
        [[tap rac_gestureSignal] subscribeNext:^(id x) {
            @strongify(self);

            /* MARK: ================= 弹出头像弹窗 =================*/
            
            QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                
            }];
            
            
            QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"自定义头像" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                [self presentImagePicker];
            }];
            
            QMUIAlertAction *action4 = [QMUIAlertAction actionWithTitle:@"选择默认头像" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                if (1)[self.getNav pushViewController:[[MeSetUsetImg alloc]init] animated:YES];
            }];
            
            
            QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
            
            [alertController addAction:action1];
            [alertController addAction:action2];
            [alertController addAction:action4];
            
            [alertController showWithAnimated:YES];
            
        }];
        [_picUser addGestureRecognizer:tap];
    }
    return _picUser;
}

-(QMUILabel *)labUserName{
    if (!_labUserName) {
        _labUserName = [[QMUILabel alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.picUser.frame)+25, kScreenW, 25)];
        _labUserName.userInteractionEnabled = YES;
        _labUserName.font = [UIFont fontWithName:@"Helvetica-Bold" size:22];
        _labUserName.text = @"用户名称";
        _labUserName.textAlignment = 1;
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] init];
        [[tap2 rac_gestureSignal] subscribeNext:^(id x) {
            NSLog(@"tap2");
            [self revampedUserName];
        }];
        [_labUserName addGestureRecognizer:tap2];
    }
    return _labUserName;
}

-(void)revampedUserName{
    QMUIDialogTextFieldViewController *dialogViewController = [[QMUIDialogTextFieldViewController alloc] init];
    dialogViewController.title = @"请输入昵称";
    
    [dialogViewController addTextFieldWithTitle:@"名称" configurationHandler:^(QMUILabel *titleLabel, QMUITextField *textField, CALayer *separatorLayer) {
        textField.placeholder = @"不超过10个字符";
        textField.maximumTextLength = 10;
    }];
    
    dialogViewController.enablesSubmitButtonAutomatically = NO;// 为了演示效果与第二个 cell 的区分开，这里手动置为 NO，平时的默认值为 YES
    
    
    [dialogViewController addCancelButtonWithText:@"取消" block:nil];
    [dialogViewController addSubmitButtonWithText:@"确定" block:^(QMUIDialogTextFieldViewController *aDialogViewController) {
        NSString *name = [aDialogViewController.textFields.firstObject.text removeSpaceAndNewline];
        
        if (name.length > 0&&name.length <8) {
            
            /* TODO: ================= 修改名称 =================*/
            
            NSString *name = aDialogViewController.textFields.firstObject.text;
            @weakify(self);
            
            [[AccountService loadsaveUserInfo:name]subscribeNext:^(ResponseData  *x) {
                @strongify(self);
                if (x.success) {
                    kUSER_INFO_MANAGER.nickName = name;
                    [kUSER_INFO_MANAGER MyList];
                    //                    self.UserName.text = aDialogViewController.textFields.firstObject.text;
                    [Tools showTips:@"修改成功"];
                    
                }else{
                    [QMUITips showError:x.errorInfo];
                }
                
            }];
            
        } else {
            [Tools showTips:@"不能为空或者超过8个长度"];
        }
        [aDialogViewController hide];
    }];
    
    [dialogViewController show];
    self.currentTextFieldDialogViewController = dialogViewController;
}

-(QMUILabel *)labUserPhone{
    if (!_labUserPhone) {
        _labUserPhone = [[QMUILabel alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.labUserName.frame)+16, kScreenW, 18)];
        _labUserPhone.font = [UIFont fontWithName:@"Helvetica-Bold" size:22];
        _labUserPhone.text = @"13713855641";
        _labUserPhone.textColor = baseColorMedium;
        _labUserPhone.textAlignment = 1;
    }
    return _labUserPhone;
}

-(QMUIButton *)btnReceive{
    if (!_btnReceive) {
        _btnReceive = [[QMUIButton alloc]init];
        _btnReceive.frame = CGRectMake(14,CGRectGetMaxY(self.labUserPhone.frame)+kScreenH/100*12, kScreenW-28, 44);
        _btnReceive.titleLabel.font = [UIFont systemFontOfSize:16];
        [_btnReceive setCornerRadiusWithRadius:8 isMasks:YES];
        [_btnReceive setBorderWithColor:[UIColor blackColor] width:2];
        [_btnReceive setTitle:@"我的消息" forState:UIControlStateNormal];
        [_btnReceive setTitle:@"3新条消息" forState:UIControlStateSelected];
        [_btnReceive setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_btnReceive setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnReceive.backgroundColor = [UIColor whiteColor];
        
        @weakify(self);
        [[_btnReceive rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            
            Ugc_Receive_VC_WX *vc = [[Ugc_Receive_VC_WX alloc]init];
            [self.getNav pushViewController:vc animated:YES];
            
            if (!self.btnReceive.selected) {
                self.btnReceive.selected = !self.btnReceive.selected;
            }else{
             
            }

        }];
    }
    return _btnReceive;
}

-(QMUIButton *)btnHome{
    if (!_btnHome) {
        _btnHome = [[QMUIButton alloc]init];
        _btnHome.frame = CGRectMake(14,CGRectGetMaxY(self.btnReceive.frame)+18, kScreenW-28, 44);
        _btnHome.titleLabel.font = [UIFont systemFontOfSize:16];
        [_btnHome setCornerRadiusWithRadius:8 isMasks:YES];
        [_btnHome setBorderWithColor:[UIColor blackColor] width:2];
        [_btnHome setTitle:@"我的主页" forState:UIControlStateNormal];
        [_btnHome setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnHome.backgroundColor = [UIColor whiteColor];
        @weakify(self);
        
        [[_btnHome rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
          
            Ugc_HomePage_VC_V3 *vc = [[Ugc_HomePage_VC_V3 alloc]init];
            vc.userName = kUSER_INFO_MANAGER.nickName;
            vc.userId = kUSER_INFO_MANAGER.userId;
            vc.userAvatar = kUSER_INFO_MANAGER.avatar;

            [self.getNav pushViewController:vc animated:YES];
            /* TODO: ================= 点击跳转到 APPSTORRE =================*/
        }];
    }
    return _btnHome;
}

-(QMUIButton *)btnLike{
    if (!_btnLike) {
        _btnLike = [[QMUIButton alloc]init];
        _btnLike.frame = CGRectMake(14,CGRectGetMaxY(self.btnHome.frame)+18, kScreenW-28, 44);
        _btnLike.titleLabel.font = [UIFont systemFontOfSize:16];
        [_btnLike setCornerRadiusWithRadius:8 isMasks:YES];
        [_btnLike setBorderWithColor:[UIColor blackColor] width:2];
        [_btnLike setTitle:@"我点赞的创作" forState:UIControlStateNormal];
        [_btnLike setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnLike.backgroundColor = [UIColor whiteColor];
        @weakify(self);
        
        [[_btnLike rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            Ugc_MyLaud_VC *vc = [[Ugc_MyLaud_VC alloc]init];
            [self.getNav pushViewController:vc animated:YES];
        }];
    }
    return _btnLike;
}

-(QMUIButton *)btnSetUP{
    if (!_btnSetUP) {
        _btnSetUP = [[QMUIButton alloc]init];
        _btnSetUP.frame = CGRectMake(14,CGRectGetMaxY(self.btnLike.frame)+18, kScreenW-28, 44);
        _btnSetUP.titleLabel.font = [UIFont systemFontOfSize:16];
        [_btnSetUP setCornerRadiusWithRadius:8 isMasks:YES];
        [_btnSetUP setBorderWithColor:[UIColor blackColor] width:2];
        [_btnSetUP setTitle:@"退出登录" forState:UIControlStateNormal];
        [_btnSetUP setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnSetUP.backgroundColor = [UIColor whiteColor];
        @weakify(self);
        [[_btnSetUP rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            /* !!!: ================= 登出 ================= */
            [[AccountService loaduserLoginOut]subscribeNext:^(ResponseData * x) {
                
                if (x.success) {
                    [Tools showTips:@"退出成功"];
                }else{
                    [QMUITips showError:x.errorInfo];
                }
                
            }];
            
            // 移除别名
            [UMessage removeAlias:kUSER_INFO_MANAGER.userId type:@"userId" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                NSLog(@"");
            }];
            
            [kUSER_INFO_MANAGER removeUserInfo];
            [kUSER_INFO_MANAGER cleanCookie];
            kUSER_INFO_MANAGER.getMyEnquiryList = NO;
            kUSER_INFO_MANAGER.getFollowGoods = NO;

        }];
    }
    return _btnSetUP;
}


/* MARK: ================= 上传用户头像图片 =================*/
#pragma mark - 打开图片浏览器
-(void)presentImagePicker{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    picker.allowPickingVideo = NO;
    picker.allowTakeVideo = NO;
    
    [picker setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        
        if (photos.count > 0) {
            
            // 添加了图片 先上传到服务器
            UIImage *image = photos.firstObject;
            //上传腾讯云服务器上
            [kNetworkShared getImageURLWithImage:image completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
                
                if (isSuccess) {
                    
                    NSString * avatar = kSTRING_FORMAT(@"%@/%@",filePath,fileName);
                    //                NSDictionary *dic = @{@"token":kUSER_INFO_MANAGER.token,@"avatar":avatar,@"id":kUSER_INFO_MANAGER.userId};
                    NSLog(@"");
                    @weakify(self);
                    [[AccountService loadsaveUserAvatar:avatar]subscribeNext:^(ResponseData *x) {
                        @strongify(self);
                        if (x.success) {
                            [Tools showTips:@"修改成功"];
                            
                            kUSER_INFO_MANAGER.avatar = avatar;
                            [kUSER_INFO_MANAGER MyList];
                            [self.getNav popViewControllerAnimated:YES];
                            
                            //                            [[AccountService loadLogin:str phoneCode:@"8888" reponseObjctClass:[UserInfoManager class]]subscribeNext:^(ResponseData * x) {
                            //                                if (x.success) {
                            //                                    [kUSER_INFO_MANAGER MyList];
                            //                                    ResponseData *data = x;
                            //                                    UserInfoManager *model = data.responseData;
                            //                                    [kUSER_INFO_MANAGER setUserInfoWithModel:model];
                            //                                }else{
                            //                                    [QMUITips showError:x.errorInfo];
                            //                                }
                            ////                                [self.navigationController popViewControllerAnimated:YES];
                            //                            }];
                            
                        }else{
                            [QMUITips showError:x.errorInfo];
                        }
                    }];
                }else{
                    [QMUITips showError:@"上传失败"];
                }
            }];
            
        }
        
    }];
    
    [self.getNav presentViewController:picker animated:YES completion:nil];
    
}
@end
